package cn.walls1717.ggkt.order.service.impl;

import cn.walls1717.ggkt.client.activity.CouponInfoFeignClient;
import cn.walls1717.ggkt.client.course.CourseFeignClient;
import cn.walls1717.ggkt.client.user.UserInfoFeignClient;
import cn.walls1717.ggkt.exception.MyException;
import cn.walls1717.ggkt.model.activity.CouponInfo;
import cn.walls1717.ggkt.model.order.OrderDetail;
import cn.walls1717.ggkt.model.order.OrderInfo;
import cn.walls1717.ggkt.model.user.UserInfo;
import cn.walls1717.ggkt.model.vod.Course;
import cn.walls1717.ggkt.order.mapper.OrderInfoMapper;
import cn.walls1717.ggkt.order.service.OrderDetailService;
import cn.walls1717.ggkt.order.service.OrderInfoService;
import cn.walls1717.ggkt.util.AuthContextHolder;
import cn.walls1717.ggkt.util.OrderNoUtils;
import cn.walls1717.ggkt.vo.order.OrderFormVo;
import cn.walls1717.ggkt.vo.order.OrderInfoQueryVo;
import cn.walls1717.ggkt.vo.order.OrderInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单表服务实现类
 *
 * @author walls1717
 * @since 2022/07/17
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private CourseFeignClient courseFeignClient;

    @Autowired
    private CouponInfoFeignClient couponInfoFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    /**
     * 订单列表
     */
    @Override
    public Page<OrderInfo> listPages(Integer pageNum, Integer pageSize, OrderInfoQueryVo orderInfoQueryVo) {
        Page<OrderInfo> orderInfoPage = new Page<>(pageNum, pageSize);
        Long userId = orderInfoQueryVo.getUserId();
        // 订单交易块
        String outTradeNo = orderInfoQueryVo.getOutTradeNo();
        String phone = orderInfoQueryVo.getPhone();
        String createTimeEnd = orderInfoQueryVo.getCreateTimeEnd();
        String createTimeBegin = orderInfoQueryVo.getCreateTimeBegin();
        Integer orderStatus = orderInfoQueryVo.getOrderStatus();

        LambdaQueryWrapper<OrderInfo> lqw = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(userId)) {
            lqw.eq(OrderInfo::getUserId, userId);
        }
        if (!StringUtils.isEmpty(outTradeNo)) {
            lqw.eq(OrderInfo::getOutTradeNo, outTradeNo);
        }
        if (!StringUtils.isEmpty(phone)) {
            lqw.eq(OrderInfo::getPhone, phone);
        }
        // >=createTime
        if (!StringUtils.isEmpty(createTimeBegin)) {
            lqw.ge(OrderInfo::getCreateTime, createTimeBegin);
        }
        // <= createTime
        if (!StringUtils.isEmpty(createTimeEnd)) {
            lqw.le(OrderInfo::getCreateTime, createTimeEnd);
        }
        if (!StringUtils.isEmpty(orderStatus)) {
            lqw.eq(OrderInfo::getOrderStatus, orderStatus);
        }
        this.page(orderInfoPage, lqw);
        List<OrderInfo> records = orderInfoPage.getRecords();
        // 设置课程名
        records = records.stream().peek(item -> {
            Long orderId = item.getId();
            OrderDetail orderDetail = orderDetailService.getById(orderId);
            String courseName = orderDetail.getCourseName();
            item.getParam().put("courseName", courseName);
        }).collect(Collectors.toList());
        orderInfoPage.setRecords(records);
        return orderInfoPage;
    }

    /**
     * 新增点播课程订单
     */
    @Override
    public Long saveSubmitOrder(OrderFormVo orderFormVo) {
        // 课程id
        Long courseId = orderFormVo.getCourseId();
        // 优惠券id
        Long couponId = orderFormVo.getCouponId();
        // 用户id
        Long userId = AuthContextHolder.getUserId();

        // 判断当前用户是否已生成当前课程的订单
        LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getId, courseId).eq(OrderDetail::getUserId, userId);
        OrderDetail orderDetailExist = orderDetailService.getOne(lqw);
        if (orderDetailExist != null) {
            return orderDetailExist.getId();
        }

        // 根据课程id查询课程
        Course course = courseFeignClient.innerGetCourseById(courseId);
        if (course == null) {
            throw new MyException(20001, "课程不存在");
        }

        UserInfo userInfo = userInfoFeignClient.innerGetUserById(userId);
        if (userInfo == null) {
            throw new MyException(20001, "用户不存在");
        }

        BigDecimal couponReduce = new BigDecimal(0);
        if (couponId != null) {
            CouponInfo couponInfo = couponInfoFeignClient.innerGetCouponById(couponId);
            couponReduce = couponInfo.getAmount();
        }

        // 创建订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userInfo.getNickName());
        orderInfo.setPhone(userInfo.getPhone());
        orderInfo.setProvince(userInfo.getProvince());
        orderInfo.setOriginAmount(course.getPrice());
        orderInfo.setCouponReduce(couponReduce);
        orderInfo.setFinalAmount(orderInfo.getOriginAmount().subtract(orderInfo.getCouponReduce()));
        orderInfo.setOutTradeNo(OrderNoUtils.getOrderNo());
        orderInfo.setTradeBody(course.getTitle());
        orderInfo.setOrderStatus("0");
        this.save(orderInfo);

        // 创建订单详情
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orderInfo.getId());
        orderDetail.setUserId(userId);
        orderDetail.setCourseId(courseId);
        orderDetail.setCourseName(course.getTitle());
        orderDetail.setCover(course.getCover());
        orderDetail.setOriginAmount(course.getPrice());
        orderDetail.setCouponReduce(new BigDecimal(0));
        orderDetail.setFinalAmount(orderDetail.getOriginAmount().subtract(orderDetail.getCouponReduce()));
        orderDetailService.save(orderDetail);

        // 更新优惠券状态
        if (null != orderFormVo.getCouponUseId()) {
            couponInfoFeignClient.innerUpdateCouponInfoUseStatus(orderFormVo.getCouponUseId(), orderInfo.getId());
        }
        return orderInfo.getId();
    }

    @Override
    public OrderInfoVo getOrderInfoById(Long id) {
        OrderInfo orderInfo = this.getById(id);
        OrderDetail orderDetail = orderDetailService.getById(id);

        OrderInfoVo orderInfoVo = new OrderInfoVo();
        BeanUtils.copyProperties(orderInfo, orderInfoVo);
        orderInfoVo.setCourseId(orderDetail.getCourseId());
        orderInfoVo.setCourseName(orderDetail.getCourseName());
        return orderInfoVo;
    }

    /**
     * 更新订单状态
     */
    @Override
    public void updateOrderStatus(String out_trade_no) {
        LambdaQueryWrapper<OrderInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderInfo::getOutTradeNo, out_trade_no);
        OrderInfo orderInfo = this.getOne(lqw);
        //更新订单状态 1 已经支付
        orderInfo.setOrderStatus("1");
        this.updateById(orderInfo);
    }


}
